import { updateQueue } from "./component";

//dom:button  eventType:'onclick'  handler:事件处理函数
export default function addEvent(dom, eventType, handler) {
    // dom对应的事件处理通过store采取键值对存储
    let store = dom.store || (dom.store = {});
    store[eventType] = handler;

    //事件委派到祖先节点
    if (store[eventType]) {
        document[eventType] = dispatchEventFun;
    }
}

// document.onclick = function (event) {};
function dispatchEventFun(event) {
    let { target, type } = event;

    let eventType = "on" + type;
    // 通过target找出对应的是哪个dom的触发
    let { store } = target;
    if (!store) {
        return;
    }
    let handler = store[eventType];
    updateQueue.isBatchData = true;
    let syntheticBaseEvent = createBaseEvent(event);
    handler && handler(syntheticBaseEvent);

    updateQueue.isBatchData = false;
    updateQueue.batchUpdate();
}

// 对event的特性做各浏览器的兼容性处理
function createBaseEvent(event) {
    let syntheticBaseEvent = {};
    for (const key in event) {
        syntheticBaseEvent[key] = event[key];
    }
    syntheticBaseEvent.nativeEvent = event;
    // 比如兼容preventDefault
    syntheticBaseEvent.preventDefault = preventDefault;
    return syntheticBaseEvent;
}

function preventDefault(event) {
    if (!event) {
        // 兼容IE
        window.event.returnValue = false;
    }

    if (event.preventDefault) {
        event.preventDefault();
    }
}
